package com.yxjx.duoxue.course;

import java.util.ArrayList;
import java.util.Hashtable;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.yxjx.duoxue.datamodel.DMArea;
import com.yxjx.duoxue.datamodel.DMBaiduLocation;
import com.yxjx.duoxue.datamodel.DMCourseCategory;
import com.yxjx.duoxue.datamodel.DMSortBy;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.utils.UIHelper;

/**
 * store user's current selection info.
 * @author mengmengchen
 *
 */
public class SearchCondition {
	// 默认设置都是不作为条件。
	// 课程类别
	public static final int FILTER_BY_RECOMMENDS = 4;// 用作显示推荐列表。

	
	private boolean mCourseTypeIgnore = true;
	private int mCourseCategoryOne;
	private int mCourseCategoryTwo;
	// 区域
	private boolean mColumn2AreaIgnore = true;
	private int mAreaCategoryOne;
	private int mAreaCategoryTwo;
	// 年龄
	private boolean mColumn3Ignore = true;
	private int mStartAge;
	private int mEndAge;
	// 排序方式
	// 1 默认排序 （default）
	// 2 最新发布
	// 3 收藏最多
	// 4 免费试听
	private static String[] sortBys = new String[] {
			"智能排序",
			"最新发布",
			"收藏最多",
			"免费试听"
	};
	
	// 分别存放course和school列表的排序方式
	private int mColumn4SortByOfCourse = 0;
	private int mColumn4SortByOfSchool = 0;
	
	private String mKeyword = "";
	
	// 位置信息（位置变化也意味着查询条件发生变化）
	private double latitude = .0;
	private double longtitude = .0;


	private Context mContext;
	
	public SearchCondition(Context ctx) {
		setContext(ctx);
		setCourseTypeIgnore(true);
		
		// 记录当前的位置信息
		DMBaiduLocation loc = Globals.getInstance(mContext).getLocation();
		if (loc != null) {
			setLatitude(loc.getLatitude());
			setLongtitude(loc.getLongtitude());
		}
	}
 	
	public boolean isCourseTypeIgnore() {
		return mCourseTypeIgnore;
	}
	public void setCourseTypeIgnore(boolean mCourseTypeIgnore) {
		this.mCourseTypeIgnore = mCourseTypeIgnore;
	}
	public int getCourseCategoryOne() {
		return mCourseCategoryOne;
	}
	public void setCourseCategoryOne(int mCourseCategoryOne) {
		this.mCourseCategoryOne = mCourseCategoryOne;
	}
	public int getCourseCategoryTwo() {
		return mCourseCategoryTwo;
	}
	public void setCourseCategoryTwo(int mCourseCategoryTwo) {
		this.mCourseCategoryTwo = mCourseCategoryTwo;
	}
	public boolean isColumn2Ignore() {
		return mColumn2AreaIgnore;
	}
	public void setAreaIgnore(boolean mColumn2Ignore) {
		this.mColumn2AreaIgnore = mColumn2Ignore;
	}
	public int getAreaCategoryTwo() {
		return mAreaCategoryTwo;
	}
	public void setAreaCategoryTwo(int mAreaCategoryTwo) {
		this.mAreaCategoryTwo = mAreaCategoryTwo;
	}
	public int getAreaCategoryOne() {
		return mAreaCategoryOne;
	}
	public void setAreaCategoryOne(int mAreaCategoryOne) {
		this.mAreaCategoryOne = mAreaCategoryOne;
	}
	public boolean isColumn3Ignore() {
		return mColumn3Ignore;
	}
	public void setColumn3Ignore(boolean mColumn3Ignore) {
		this.mColumn3Ignore = mColumn3Ignore;
	}
	public int getStartAge() {
		return mStartAge;
	}
	public void setStartAge(int mStartAge) {
		this.mStartAge = mStartAge;
	}
	public int getEndAge() {
		return mEndAge;
	}
	public void setEndAge(int mEndAge) {
		this.mEndAge = mEndAge;
	}
	public int getColumn4SortBy(int headTabSelected) {
		if (headTabSelected == CourseListActivity.HEAD_TAB_COURSE) {
			return mColumn4SortByOfCourse;
		} else {
			return mColumn4SortByOfSchool;
		}
	}
	/**
	 * 返回sortBy对象中的Id，用于作为条件查询的条件。
	 * @param headTabSelected
	 * @return
	 */
	private int getColumn4SortByInternal(int headTabSelected) {
		if (headTabSelected == CourseListActivity.HEAD_TAB_COURSE) {
			ArrayList<DMSortBy> courseSortBy = Globals.getInstance(mContext).getSortBysCourse();
			return (courseSortBy == null || courseSortBy.size() <= mColumn4SortByOfCourse) ? 0 : courseSortBy.get(mColumn4SortByOfCourse).getSortById();
		} else {
			ArrayList<DMSortBy> schoolSortBy = Globals.getInstance(mContext).getSortBysSchool();
			return (schoolSortBy == null || schoolSortBy.size() <= mColumn4SortByOfSchool) ? 0 : schoolSortBy.get(mColumn4SortByOfSchool).getSortById();
		}
	}
	
	public void setColumn4SortBy(int mColumn4SortBy, int headTabSelected) {
		if (headTabSelected == CourseListActivity.HEAD_TAB_COURSE) {
			this.mColumn4SortByOfCourse = mColumn4SortBy;
		} else {
			this.mColumn4SortByOfSchool = mColumn4SortBy;
		}
	}
	
	/**
	 * The text should be shown in search condition area after user change search condition.
	 * @param headTabSelected
	 * @param tabIndex
	 * @param column1Index
	 * @param column2Index
	 * @return
	 */
	public static String getTag(Context ctx, int headTabSelected, int tabIndex, int column1Index, int column2Index) {
		String ret = "";
		switch (tabIndex) {
		case CourseListActivity.TAB_COURSE:
			ArrayList<ArrayList<DMCourseCategory>> types = Globals.getInstance(ctx).getCourseTpes();
			ArrayList<DMCourseCategory> subtypes = types.get(column1Index);
			if (column2Index == 0) {
				ret = subtypes.get(0).getStr();
			} else {
				// 一级分类项占一个，“全部”占一个
				ret = subtypes.get(column2Index + 1).getStr();
			}
			break;
		case CourseListActivity.TAB_AREA:
			ArrayList<ArrayList<DMArea>> areas = Globals.getInstance(ctx).getAreasInfo();
			ArrayList<DMArea> subAreas = areas.get(column1Index);
			if (column2Index == 0) {
				ret = subAreas.get(0).getAreaName();
			} else {
				// 一级分类项占一个，“全部”占一个
				ret = subAreas.get(column2Index + 1).getAreaName();
			}
			break;
		case CourseListActivity.TAB_AGE:
			if (column1Index == 0) {
				ret = "年龄";
			} else {
				ret = "" + getAgeDes(column1Index);
			}
			break;
		case CourseListActivity.TAB_SMART:
			ret = DMSortBy.getTag(ctx, headTabSelected, column1Index);
			break;
		default:
			break;
		}
		return ret;
		
	}
	
	public void resetAsDefault(int headTabSelected) {
		setCourseTypeIgnore(true);
		setAreaIgnore(true);
		setColumn3Ignore(true);
		setColumn4SortBy(0, headTabSelected);
	}
	
	public DMCourseCategory getCourseCategory() {
		DMCourseCategory ret = null;
		ArrayList<ArrayList<DMCourseCategory>> types = Globals.getInstance(mContext).getCourseTpes();
		ArrayList<DMCourseCategory> subtypes = types.get(mCourseCategoryOne);
		if (mCourseCategoryTwo == 0) {
			ret = subtypes.get(0);
		} else {
			// 一级分类项占一个，“全部”占一个
			ret = subtypes.get(mCourseCategoryTwo + 1);
		}
		return ret;
	}
	
	public DMArea getArea() {
		DMArea ret = null;
		ArrayList<ArrayList<DMArea>> areas = Globals.getInstance(mContext).getAreasInfo();
		ArrayList<DMArea> row = areas.get(mAreaCategoryOne);
		if (mAreaCategoryTwo == 0 && !"附近".equals(row.get(0).getAreaName())) {
			ret = row.get(0);
		} else {
			// 一级分类项占一个，“全部”占一个
			ret = row.get(mAreaCategoryTwo + 1);
		}
		
		return ret;
	}
	
	/**
	 * get current QueryCondtion
	 * @return
	 */
	public JSONObject getQueryCondition(int headTabSelected) {
		JSONObject ret = new JSONObject();
		try {
			// 课程类别
			if (!isCourseTypeIgnore()) {
				DMCourseCategory category = getCourseCategory();
				if (category != null) {
					ret.put(NwUtils.KEY_CATEGORY, category.getType());
				}
			}

			// 区域查询
			if (!isColumn2Ignore()) {
				DMArea area = getArea();
				if (area != null) {
					ret.put(NwUtils.KEY_AREA, "" + area.getLevel() + "_" + area.getId());
				}
			} else {
				ret.put(NwUtils.KEY_AREA, "0_0");
			}
			
			if (!isColumn3Ignore()) {
				ret.put(NwUtils.KEY_AGE, "" + getStartAge() + "_" + getEndAge());
			}
			
			// sort by
			ret.put(NwUtils.KEY_ORDER_BY, "" + getColumn4SortByInternal(headTabSelected));
			ret.put(NwUtils.KEY_KEYWORD, "" + getKeyword());
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return ret;
	}
	
	/**
	 * 推荐课程的查询条件
	 * @return
	 */
	public static JSONObject getRecommendCoursesParam() {
		JSONObject params = new JSONObject();
		try {
			params.put(NwUtils.KEY_START_INDEX, "0");
			params.put("count", HomePageFragment.COUNT_GENERAL_ITEM);
			params.put(NwUtils.KEY_ORDER_BY, FILTER_BY_RECOMMENDS);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return params;
	}
	/**
	 * 通过传入的课程类型ID确定当前设置的查询条件。
	 * @param courseTypeId
	 * @param headTabSelected
	 */
	public void resetCategory(int courseTypeId, int headTabSelected) {
		if (courseTypeId < 0) {
			return;
		}
		ArrayList<ArrayList<DMCourseCategory>> types = Globals.getInstance(mContext).getCourseTpes();
		if (types == null) {
			return;
		}
		for (int column1 = 0; column1 < types.size(); column1 ++) {
			ArrayList<DMCourseCategory> subtypes = types.get(column1);
			DMCourseCategory item = subtypes.get(0);
			if (courseTypeId == item.getType()) {
				setCourseTypeIgnore(false);
				setCourseCategoryOne(column1);
				setCourseCategoryTwo(0);
				setColumn4SortBy(0, headTabSelected);
				break;
			}
			for (int column2 = 2; column2 < subtypes.size(); column2 ++) {
				DMCourseCategory item2 = subtypes.get(column2);
				if (courseTypeId == item2.getType()) {
					setCourseTypeIgnore(false);
					setCourseCategoryOne(column1);
					setCourseCategoryTwo(column2 - 1);
					setColumn4SortBy(0, headTabSelected);
					break;
				}
			}
		}
	}
	
	/**
	 * 通过Text来确定当前设置的查询条件
	 * when launch course list from home page, then update the search condition by category text.
	 * @param text
	 */
	public void resetCategory(String text, int headTabSelected) {
		if (UIHelper.isEmpty(text)) {
			return;
		}
		ArrayList<ArrayList<DMCourseCategory>> types = Globals.getInstance(mContext).getCourseTpes();
		if (types == null) {
			return;
		}
		for (int column1 = 0; column1 < types.size(); column1 ++) {
			ArrayList<DMCourseCategory> subtypes = types.get(column1);
			DMCourseCategory item = subtypes.get(0);
			if (text.equals(item.getStr())) {
				setCourseTypeIgnore(false);
				setCourseCategoryOne(column1);
				setCourseCategoryTwo(0);
				setColumn4SortBy(0, headTabSelected);
				break;
			}
			for (int column2 = 2; column2 < subtypes.size(); column2 ++) {
				DMCourseCategory item2 = subtypes.get(column2);
				if (text.equals(item2.getStr())) {
					setCourseTypeIgnore(false);
					setCourseCategoryOne(column1);
					setCourseCategoryTwo(column2 - 1);
					setColumn4SortBy(0, headTabSelected);
					break;
				}
			}
		}
	}

	public String getKeyword() {
		return mKeyword;
	}

	public void setKeyword(String mKeyword) {
		this.mKeyword = mKeyword;
	}
	
	/**
	 * copy a instance of SearchCondtion
	 * @return
	 */
	public SearchCondition copy(int headTabSelected) {
		SearchCondition condition = new SearchCondition(null);
		condition.setContext(getContext());
		
		condition.setCourseTypeIgnore(this.isCourseTypeIgnore());
		condition.setCourseCategoryOne(this.getCourseCategoryOne());
		condition.setCourseCategoryTwo(this.getCourseCategoryTwo());
		
		condition.setAreaIgnore(this.isColumn2Ignore());
		condition.setAreaCategoryOne(this.getAreaCategoryOne());
		condition.setAreaCategoryTwo(this.getAreaCategoryTwo());
		
		condition.setColumn3Ignore(this.isColumn3Ignore());
		condition.setEndAge(getEndAge());
		condition.setStartAge(getStartAge());
		
		condition.setColumn4SortBy(this.getColumn4SortBy(headTabSelected), headTabSelected);
		condition.mColumn4SortByOfCourse = this.mColumn4SortByOfCourse;
		condition.mColumn4SortByOfSchool = this.mColumn4SortByOfSchool;
		condition.setKeyword(getKeyword());
		
		condition.setLatitude(this.getLatitude());
		condition.setLongtitude(this.getLongtitude());
		
		return condition;
	}
	
	/**
	 * If current conditon is equals with the last School condition.
	 * @param last
	 * @return
	 */
	public boolean equalsToSchoolCondition(SearchCondition last, int headTabSelected) {
		return isCourseTypeIgnore() == last.isCourseTypeIgnore()
				&& getCourseCategoryOne() == last.getCourseCategoryOne()
				&& getCourseCategoryTwo() == last.getCourseCategoryTwo()
				&& isColumn2Ignore() == last.isColumn2Ignore()
				&& getAreaCategoryOne() == last.getAreaCategoryOne()
				&& getAreaCategoryTwo() == last.getAreaCategoryTwo()
				&& isColumn3Ignore() == last.isColumn3Ignore()
				&& getEndAge() == last.getEndAge()
				&& getStartAge() == last.getStartAge()
				&& getColumn4SortBy(headTabSelected) == last.getColumn4SortBy(headTabSelected)
				&& UIHelper.isEqual(getKeyword(), last.getKeyword())
				&& getLatitude() == last.getLatitude()
				&& getLongtitude() == last.getLongtitude();
	}
	
	/**
	 * If current conditon is equals with the last Course Condition.
	 * @param last
	 * @return
	 */
	public boolean equalsToCourseCondition(SearchCondition last, int headTabSelected) {
		return isCourseTypeIgnore() == last.isCourseTypeIgnore()
				&& getCourseCategoryOne() == last.getCourseCategoryOne()
				&& getCourseCategoryTwo() == last.getCourseCategoryTwo()
				&& isColumn2Ignore() == last.isColumn2Ignore()
				&& getAreaCategoryOne() == last.getAreaCategoryOne()
				&& getAreaCategoryTwo() == last.getAreaCategoryTwo()
				&& isColumn3Ignore() == last.isColumn3Ignore()
				&& getColumn4SortBy(headTabSelected) == last.getColumn4SortBy(headTabSelected)
				&& UIHelper.isEqual(getKeyword(), last.getKeyword())
				&& getLatitude() == last.getLatitude()
				&& getLongtitude() == last.getLongtitude();
	}

	/**
	 * 设置默认的查询area条件（附近－>智能范围）
	 * @param area
	 */
	public void resetArea(String area) {
		if (UIHelper.isEmpty(area)) {
			return;
		}
		ArrayList<ArrayList<DMArea>> types = Globals.getInstance(mContext).getAreasInfo();
		if (types == null) {
			return;
		}
		for (int index = 0; index < types.size(); index ++) {
			ArrayList<DMArea> subtypes = types.get(index);
			DMArea item = subtypes.get(0);
			if (area.equals(item.getAreaName())) {
				setAreaIgnore(false);
				setAreaCategoryOne(index);
				setAreaCategoryTwo(0);
				return;
			}
		}
		
	}

	// map age condition to startAge and endAge [begin]
	private static String[] ages = new String[] {
			"全部","1岁以下","1-3岁","4-6岁","7-12岁","13-15岁","16-18岁","18岁以上"
	};
	
	public static ArrayList<String> getAges() {
		ArrayList<String> strs = new ArrayList<String>();
		for (String age : ages) {
			strs.add(age);
		}
		return strs;
	}
	
	public static String getAgeDes(int index) {
		if (index < 0 || index  >= ages.length) {
			return "";
		}
		return ages[index];
	}
	
	public static int indexToBeginAge(int index) {
		String text = getAgeDes(index);
		if (UIHelper.isEmpty(text)) {
			return 0;
		}
		
		Hashtable<String, Integer> map = new Hashtable<String, Integer>() {
			{
				put("全部", 0);
				put("1岁以下", 0);
				put("1-3岁", 1);
				put("4-6岁", 4);
				put("7-12岁", 7);
				put("13-15岁", 13);
				put("16-18岁", 16);
				put("18岁以上", 19);
			}
		};
		
		if (map.containsKey(text)) {
			return map.get(text);
		}
		return 0;
	}
	
	public static int indexToEndAge(int index) {
		String text = getAgeDes(index);
		if (UIHelper.isEmpty(text)) {
			return 100;
		}
		
		Hashtable<String, Integer> map = new Hashtable<String, Integer>() {
			{
				put("全部", 100);
				put("1岁以下", 1);
				put("1-3岁", 4);
				put("4-6岁", 7);
				put("7-12岁", 13);
				put("13-15岁", 16);
				put("16-18岁", 19);
				put("18岁以上", 100);
			}
		};
		
		if (map.containsKey(text)) {
			return map.get(text);
		}
		return 100;
	}
	//[end]
	
	// 用于显示当前的选中状态
	public int[] getSelectedIndexOfColumn1() {
		int[] ret = new int[2];
		if (mColumn2AreaIgnore) {
			ret[0] = 0;
			ret[1] = -1;
		} else {
			ret[0] = mAreaCategoryOne;
			ret[1] = mAreaCategoryTwo;
		}
		return ret;

	}

	public int[] getSelectedIndexOfColumn2() {
		int[] ret = new int[2];
		if (mCourseTypeIgnore) {
			ret[0] = 0;
			ret[1] = -1;
		} else {
			ret[0] = mCourseCategoryOne;
			ret[1] = mCourseCategoryTwo;
		}
		return ret;
	}

	public int getSelectedIndexOfColumn3() {
		if (mColumn3Ignore) {
			return 0;
		} else {
			return getIndexByBeginEndAge();
		}
	}
	
	private int getIndexByBeginEndAge() {
		for (int index = 0; index < ages.length; index++) {
			if (indexToBeginAge(index) == mStartAge && indexToEndAge(index) == mEndAge) {
				return index;
			}
		}
		return -1;
	}

	public double getLatitude() {
		return latitude;
	}

	public void setLatitude(double latitude) {
		this.latitude = latitude;
	}

	public double getLongtitude() {
		return longtitude;
	}

	public void setLongtitude(double longtitude) {
		this.longtitude = longtitude;
	}

	public Context getContext() {
		return mContext;
	}

	public void setContext(Context mContext) {
		this.mContext = mContext;
	}
	

}

